package com.yupi.loveplanneraiagent.tools;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import com.yupi.loveplanneraiagent.constant.FileConstant;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import java.io.File;

/**
 * PDF生成工具
 */
public class PDFGenerationTool {

    @Tool(description = "Generate a PDF document with the provided content")
    public String generatePDF(
            @ToolParam(description = "Name of the file to save the generated PDF") String fileName,
            @ToolParam(description = "Content to be included in the PDF") String content) {

        String fileDir = FileConstant.FILE_SAVE_DIR + "/pdf";
        String filePath = fileDir + "/" + fileName;

        if (!fileName.toLowerCase().endsWith(".pdf")) {
            filePath += ".pdf";
        }

        try {
            // 创建目录
            File dir = new File(fileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 使用 PdfWriter 创建 PDF
            PdfWriter writer = new PdfWriter(filePath);
            PdfDocument pdf = new PdfDocument(writer);

            // 创建文档对象
            Document document = new Document(pdf, PageSize.A4);

            // 设置中文字体以支持Unicode字符
            PdfFont font = null;
            try {
                // 尝试使用系统字体或iText内置字体
                font = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H",
                        PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
            } catch (Exception e) {
                // 如果默认字体失败，尝试其他字体或使用基础字体
                try {
                    font = PdfFontFactory.createFont("Helvetica", PdfEncodings.WINANSI,
                            PdfFontFactory.EmbeddingStrategy.PREFER_EMBEDDED);
                } catch (Exception ex) {
                    // 最后回退到默认字体
                    font = PdfFontFactory.createFont();
                }
            }

            // 添加标题
//            Paragraph title = new Paragraph("Generated Document")
//                    .setFont(font)
//                    .setFontSize(18)
//                    .setFontColor(ColorConstants.BLUE)
//                    .setTextAlignment(TextAlignment.CENTER)
//                    .setMarginBottom(20);
//            document.add(title);

            // 添加内容，确保内容是有效的UTF-8编码
            String sanitizedContent = sanitizeUnicodeContent(content);
            Paragraph contentPara = new Paragraph(sanitizedContent)
                    .setFont(font)
                    .setFontSize(12)
                    .setTextAlignment(TextAlignment.LEFT)
                    .setMarginBottom(10);
            document.add(contentPara);

            // 关闭文档
            document.close();

            return "PDF generated successfully at: " + filePath;

        } catch (Exception e) {
            return "Error generating PDF: " + e.getMessage();
        }
    }

    /**
     * 清理内容中的非BMP Unicode字符，将其替换为安全的替代字符
     */
    private String sanitizeUnicodeContent(String content) {
        if (content == null) {
            return "";
        }

        StringBuilder sanitized = new StringBuilder();
        for (char c : content.toCharArray()) {
            // 检查字符是否在BMP范围内（U+0000 到 U+FFFF）
            if (Character.isHighSurrogate(c) || Character.isLowSurrogate(c)) {
                // 如果是代理对的一部分，跳过处理（需要成对处理）
                sanitized.append('?'); // 替换为问号或其他安全字符
            } else if (c >= 0x10000) { // 非BMP字符
                sanitized.append('?'); // 替换为问号或其他安全字符
            } else {
                sanitized.append(c);
            }
        }

        return sanitized.toString();
    }
}
